<script setup>
import {request} from "@/util/request.js";
import {useUserStore} from "@/store/user.js";
import {onMounted, ref} from 'vue'
import {useRouter} from 'vue-router'
import {ElMessage, ElMessageBox} from 'element-plus'
import {useCartStore} from "@/store/cart.js";

const userStore = useUserStore()
const router = useRouter()
const checkAll = ref(false)
const items = ref([])
const config = {
    headers: {
        'token': userStore.token
    }
}
const cart = ref('')
// 总商品数量
const sum = ref(0)
const total = ref(0.00)
const cartStore = useCartStore()

// 获取购物车详情
function getCarts() {
    request.get('/cart/list', config).then(res => {
        if (res.code === 1) {
            items.value = res.data
        } else {
            ElMessage.error("查询购物车失败");
        }
    })
}

// 点击商品名称跳转到商品详情页
function openInfo(id) {
    router.push({
        path: '/info/' + id
    })
}

// 修改购物车商品数量
function changeQuantity(id, quantity) {
    const cart = {
        cartId: id,
        quantity: quantity
    }
    request.post('/cart/edit', cart, config).then(res => {
        if (res.code === 1) {
            checkTable()
        }
    })

}

// 格式化单价显示
function formatterPrice(row, column, cellValue) {
    return '￥' + cellValue
}

// 小计
function subTotal(row) {
    return '￥' + (row.product.price * row.quantity).toFixed(2)
}

// 删除购物车商品
function deleteCart(id) {
    ElMessageBox.confirm(
        '确认要删除嘛?',
        '警告',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        request.delete('/cart/delete/' + id, config).then(res => {
            if (res.code === 1) {
                ElMessage({
                    type: 'success',
                    message: '删除成功',
                })
                getCarts()
            }
        })
    }).catch(() => {
        ElMessage({
            type: 'info',
            message: 'Delete canceled',
        })
    })

}


// 选中结算台的全选按钮 选中所有商品
function check() {
    cart.value.toggleAllSelection()
}

// 商品列表的多选框被选中，如果全部被选中 就把结算台的 选中，并计算总价格以及总商品数量
function checkTable() {
    let selectionRows = cart.value.getSelectionRows();
    checkAll.value = selectionRows.length === items.value.length
    total.value = selectionRows.reduce((accumulator, currentRow) => {
        return accumulator + currentRow.quantity * currentRow.product.price;
    }, 0);
    sum.value = selectionRows.reduce((accumulator, currentRow) => {
        return accumulator + currentRow.quantity;
    }, 0);
}

// 删除选中的商品
function deleteProduct() {
    let selectionRows = cart.value.getSelectionRows();
    if (selectionRows.length === 0) {
        ElMessage.error("请选择要删除的商品");
        return;
    }
    let ids = selectionRows.map(item => item.cartId);
    ElMessageBox.confirm(
        '确认要删除嘛?',
        '警告',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        // TODO 删除选中的购物车商品
        request.delete('/cart/delete/' + ids, {data: ids}, config).then(res => {
            if (res.code === 1) {
                ElMessage({
                    type: 'success',
                    message: '删除成功',
                })
                getCarts()
            }
        })
    }).catch(() => {
        ElMessage({
            type: 'info',
            message: 'Delete canceled',
        })
    })
}

// 结算 -- 下单
function place() {
    let selectionRows = cart.value.getSelectionRows();
    if (selectionRows.length <= 0) {
        ElMessage.error("请至少选中一个商品！")
        return;
    }
    let arr = selectionRows.map(row => ({
        product: row.product,
        quantity: row.quantity
    }));
    // 将选中的商品信息，以及订单总价存到 状态中
    cartStore.setProducts(arr, total.value)
    // 跳转到下单页面
    router.push('/order')
}


onMounted(() => {
    getCarts()
})
</script>

<template>
    <el-table
        ref="cart"
        :data="items"
        style="width: 100%"
        @select-all="checkTable"
        @select="checkTable"
    >
        <el-table-column type="selection" label="全选" width="55"/>
        <!--商品图片及名称-->
        <el-table-column label="商品" width="520">
            <template #default="scope">
                <el-row>
                    <el-col :span="6">
                        <el-link>
                            <img :src="'/api' + scope.row.product.defaultImage.imageUrl" alt=""
                                 style="width: 100px;height: 100px" @click="openInfo(scope.row.product.productId)">
                        </el-link>
                    </el-col>
                    <!-- 商品-->
                    <el-col :span="18">
                        <el-link :underline="false" style="font-weight:bold;"
                                 @click="openInfo(scope.row.product.productId)">{{ scope.row.product.name }}
                        </el-link>
                    </el-col>
                </el-row>
            </template>
        </el-table-column>
        <el-table-column property="product.price" label="单价" :formatter="formatterPrice"/>
        <el-table-column property="quantity" label="数量">
            <template #default="scope">
                <el-input-number v-model="scope.row.quantity" :min="1" :max="10"
                                 @change="changeQuantity(scope.row.cartId, scope.row.quantity)"/>
            </template>
        </el-table-column>
        <el-table-column label="小计" :formatter="subTotal">

        </el-table-column>
        <el-table-column label="操作" width="80">
            <template #default="scope">
                <el-button type="danger" size="small" @click="deleteCart(scope.row.cartId)">删除</el-button>
            </template>
        </el-table-column>
    </el-table>
    <!--结算台-->
    <div class="total">
        <el-row style="width: 80%;margin: 0 auto;padding: 20px">
            <el-col :span="2">
                <el-checkbox v-model="checkAll" @change="check">全选</el-checkbox>
            </el-col>
            <el-col :span="9" :offset="3">
                <el-link @click="deleteProduct">删除选中的商品</el-link>
            </el-col>
            <el-col :span="10">
                <el-row>
                    <el-col :span="12">已选择{{ sum }}件商品</el-col>
                    <el-col :span="6">合计￥{{ total }}</el-col>
                    <el-col :span="3" :offset="2">
                        <el-button type="danger" size="large" @click="place">去结算</el-button>
                    </el-col>
                </el-row>
            </el-col>
        </el-row>
    </div>
</template>

<style scoped>

.total {
    width: 100%;
    background-color: #fff;
    height: 60px;
    position: fixed;
    bottom: 0;
    left: 0;
    z-index: 999;
    box-shadow: 0 0 10px #ccc;
    display: flex;
    align-items: center;
    line-height: 60px;
}

</style>